package com.jhgsys.internal.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {

    /**
     * jwt
     */
    private static final String JWT_ID = "643A";										//jwtid
    private static final String JWT_SECERT = "977ffa87f6524ad6a0518f05591effe5";			//密匙
    private static final long JWT_TTL = 5 * 60 * 1000;//5分钟
    public static final long COMMON_TTL = 2 * 60 * 60 * 1000;//2小时

    /**
     * 签发JWT
     * @param subject
     * @return
     * @throws Exception
     */
    public static String createJWT(String subject) {
        return createJWT(JWT_ID, subject, JWT_TTL);
    }

    /**
     * 签发JWT
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public static String createJWT(String subject, long ttlMillis) {
        return createJWT(JWT_ID, subject, ttlMillis);
    }

    /**
     * 签发JWT
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public static String createJWT(String id, String subject, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(signatureAlgorithm, secretKey);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static String validateJWT(String jwtStr) {
        Claims claims = parseJWT(jwtStr);
        return claims.getSubject();
    }

    /**
     * 生成subject信息
     * @param sub
     * @return
     */
    public static String generalSubject(Object sub){
        return JSONObject.toJSONString(sub);
    }

    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECERT);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    public static void main(String[] args) {
        Map<String, Object> sub = new HashMap<>();
        sub.put("username", "chenweihua@dnion.com");
        sub.put("roles", "admin");
        String subject = generalSubject(sub);
        //String token = createJWT(subject, -1);
        //System.out.println("token:" + token);

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NDNBIiwic3ViIjoie1wicm9sZXNcIjpcImFkbWluXCIsXCJ1c2VybmFtZVwiOlwiY2hlbndlaWh1YUBkbmlvbi5jb21cIn0iLCJpYXQiOjE1MjUzMzI3NjR9.DGT3G0ONaSPn7PGgU-Jhjw0HxrroejTm44QyXzBCtQ4";
        //token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NDNBIiwic3ViIjoie1wicm9sZXNcIjpcImFkbWluXCIsXCJ1c2VybmFtZVwiOlwiY2hlbndlaWh1YUBkbmlvbi5jb21cIn0iLCJpYXQiOjE1MjUzMzI2NjQsImV4cCI6MTUyNTMzMjY2NH0.QZwpQ-YwwNHJsx8lS7obLJpQcvYZQKzMC3nkfKL_WAo";
        //token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NDNBIiwic3ViIjoie1wicm9sZXNcIjpcImFkbWluXCIsXCJ1c2VybmFtZVwiOlwiY2hlbndlaWh1YUBkbmlvbi5jb21cIn0iLCJpYXQiOjE1MTUzNzg2NTgsImV4cCI6MTUxNTM3ODcxOH0.EghdtPLHo4bGU5X1QEmgyU3gd2sMYyHFCfy2hvHufT0";
        String result = validateJWT(token);
        System.out.println("result:" + result);

    }

}

